package com.cl.esjsoup.service;

import com.cl.esjsoup.jsoup.JsoupUtils;
import com.cl.esjsoup.pojo.Comment;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CommentService {
    final RestHighLevelClient client;
    private final String commentDetail;

    public CommentService(RestHighLevelClient client) {
        this.client = client;
        commentDetail = "comment_detail";
    }

    public boolean parseComment(int num) throws IOException {
        String url = "https://www.agefans.vip/catalog/all-all-all-all-all-time-";
        ArrayList<Comment> commentArrayList = JsoupUtils.getCommentArrayList(url + num);
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        IndexRequest indexRequest;
        ObjectMapper mapper = new ObjectMapper();
        for (Comment comment : commentArrayList) {
            indexRequest = new IndexRequest(commentDetail).source(mapper.writeValueAsString(comment), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    public List<Comment> list(String keyword, int pageNo, int pageSize) throws IOException {
        if (pageNo < 1) {
            pageNo = 1;
        }
        SearchRequest searchRequest = new SearchRequest(commentDetail);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.from(--pageNo * pageSize);
        sourceBuilder.size(pageSize);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder
                .field("name")
                .preTags("<span style='color:red'>")
                .postTags("</span>")
                .requireFieldMatch(false);
        sourceBuilder.highlighter(highlightBuilder);

//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyword);
        sourceBuilder.query(matchQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        List<Comment> comments = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            String newName = Arrays.stream(name.getFragments()).map(Text::toString).collect(Collectors.joining());
            Comment comment = mapper.readValue(hit.getSourceAsString(), Comment.class);
            comment.setName(newName);
            comments.add(comment);
        }
        return comments;
    }
}
